﻿using Microsoft.AspNetCore.Authorization;

namespace AuthenticationDemo.Middleware
{
    public class AllowAnonymousMiddleware
    {
        private readonly RequestDelegate _next;

        public AllowAnonymousMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            var endpoints = context.GetEndpoint();
            if (endpoints == null || !endpoints.Metadata.OfType<IAuthorizeData>().Any() || endpoints.Metadata.OfType<IAllowAnonymous>().Any())
            {
                // 如果请求标记了[AllowAnonymous] or 未使用 [Authorize]，则设置Header用于跳过身份验证
                context.Request.Headers["IsAnonymous"] = "true";
            }
            await _next(context);
        }
    }
}
